import axios from "axios";

const myAxios = axios.create({
    baseURL: "/api",
    timeout: 60000,
    withCredentials: true,
});

// 全局请求拦截器
myAxios.interceptors.request.use(
    function (config) {
        // 从localStorage获取JWT Token
        const token = localStorage.getItem('token');
        console.log(token)
        // 如果存在token则添加到请求头
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// 全局响应拦截器
myAxios.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        if (error.response && error.response.status === 401) {
            if (!window.location.pathname.includes("/user")) {
                window.location.href = `/user?redirect=${encodeURIComponent(window.location.href)}`;
            }
        }
        return Promise.reject(error);
    }
);

export default myAxios;